package com.coincalf.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.coincalf.dto.MarketDTO;
import com.coincalf.dto.TradeAreaMarketDTO;
import com.coincalf.dto.TradeMarketDTO;
import com.coincalf.entity.Market;
import com.coincalf.framework.constants.Constant;
import com.coincalf.framework.enums.DepthMergeType;
import com.coincalf.framework.enums.KlineType;
import com.coincalf.framework.enums.MarketType;
import com.coincalf.framework.enums.ResultCode;
import com.coincalf.framework.exception.GlobalDefaultException;
import com.coincalf.framework.http.Response;
import com.coincalf.framework.utils.GsonUtil;
import com.coincalf.service.EntrustOrderService;
import com.coincalf.service.MarketService;
import com.coincalf.service.TurnoverOrderService;
import com.google.common.collect.ImmutableList;
import com.huobi.client.MarketClient;
import com.huobi.client.req.market.*;
import com.huobi.constant.HuobiOptions;
import com.huobi.constant.enums.CandlestickIntervalEnum;
import com.huobi.constant.enums.DepthSizeEnum;
import com.huobi.constant.enums.DepthStepEnum;
import com.huobi.model.market.Candlestick;
import com.huobi.model.market.MarketDepth;
import com.huobi.model.market.MarketDetail;
import com.huobi.model.market.MarketTrade;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;


/**
 * @Description: 币币交易市场Controller
 * @Author: Chen Long
 * @Date: Created in 2018/5/14 上午9:57
 * @Modified by: Chen Long
 */
@Slf4j
@RestController
@RequestMapping("/trade/market")
@Api(value = "币币交易市场", description = "币币交易市场 REST API")
public class TradeMarketController implements Constant {

    @Autowired
    private MarketService marketService;
    @Autowired
    private EntrustOrderService entrustOrderService;
    @Autowired
    private TurnoverOrderService turnoverOrderService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private CommonController commonController;


    /**
     * 首页交易市场信息
     *
     * @return
     */
    @ApiIgnore
    @GetMapping("/area")
    @ApiOperation(value = "首页市场信息", notes = "首页市场信息", httpMethod = "GET")
    @ResponseBody
    public Object markets() {
        List<TradeAreaMarketDTO> tradeAreaMarket = marketService.queryTradeMarkets();
        return Response.ok(tradeAreaMarket);
    }

    /**
     * 首页交易市场信息
     *
     * @return
     */
    @GetMapping("/{areaId}")
    @ApiOperation(value = "首页市场信息", notes = "首页市场信息", httpMethod = "GET")
    @ResponseBody
    public Object markets(@PathVariable("areaId") Long areaId) {
        TradeAreaMarketDTO tradeAreaMarket = marketService.queryTradeMarkets(areaId);
        return Response.ok(tradeAreaMarket);
    }

    /**
     * 个人收藏交易市场信息
     *
     * @return
     */
    //@PreAuthorize("isAuthenticated()")
    @GetMapping("/favorite")
    @ApiOperation(value = "个人收藏交易市场信息", notes = "个人收藏交易市场信息", httpMethod = "GET")
    @ResponseBody
    public Response favorite(HttpServletRequest request) {
        Long userId = commonController.getUserId(request);
        String redisFavoriteMarket = "favorite:market:" + userId;
        List<TradeAreaMarketDTO> data = (List<TradeAreaMarketDTO>) redisTemplate.opsForValue().get(redisFavoriteMarket);
        if (!CollectionUtils.isEmpty(data)) {
            return Response.ok(data);
        }
        data = marketService.queryFavoriteTradeMarkets(userId);
        for (TradeAreaMarketDTO t : data) {
            List<TradeMarketDTO> markets = t.getMarkets();
            for (TradeMarketDTO tm : markets) {
                String symbol = tm.getSymbol().toLowerCase();
                if (!symbol.equalsIgnoreCase("AQPUSDT") && !symbol.equalsIgnoreCase("AQSUSDT")) {
                    //调用火币API获取数据
                    Candlestick candlestick;
                    try {
                        MarketClient marketClient = MarketClient.create(new HuobiOptions());
                        List<Candlestick> list = marketClient.getCandlestick(CandlestickRequest.builder()
                                .size(1)
                                .interval(CandlestickIntervalEnum.DAY1)
                                .symbol(symbol)
                                .build());
                        candlestick = list.get(0);
                        //涨跌幅 正数为涨 负数为跌
                        BigDecimal increase = candlestick.getClose().subtract(candlestick.getOpen()).multiply(BigDecimal.valueOf(100)).divide(candlestick.getOpen(), 2, RoundingMode.DOWN);
                        tm.setIncrease(increase + "%");
                        tm.setPriceUsdt(candlestick.getClose().toPlainString());
                    } catch (Exception e) {
                        log.warn("调用火币API获取数据异常 symbol={} e={}", symbol, e.getMessage());
                    }
                }
            }
        }
        redisTemplate.opsForValue().set(redisFavoriteMarket, data, 100L, TimeUnit.MILLISECONDS);
        return Response.ok(data);
    }

    /**
     * 获取K线数据
     *
     * @param symbol   获取K线数据请求参数
     * @param lintType 获取K线数据请求参数
     * @return
     */
    @GetMapping(value = "/kline/{symbol}/{lintType}/{size}")
    @ApiOperation(value = "币币交易K线数据", notes = "lineType取值范围<br/>" +
            "1min: 1分钟<br />" +
            "5min: 5分钟<br />" +
            "15min: 15分钟<br />" +
            "30min: 30分钟<br />" +
            "60min: 60分钟<br />" +
            "4hour: 4小时<br />" +
            "1day: 1天<br />" +
            "1week: 1周<br />" +
            "1mon: 1月<br />" +
            "1year: 1年<br />", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "symbol", value = "交易对标识符", required = true, dataType = "String", paramType = "path"),
            @ApiImplicitParam(name = "lintType", value = "K线类型", required = true, dataType = "String", paramType = "path"),
            @ApiImplicitParam(name = "size", value = " K线数据条数[1,2000]", required = false, dataType = "int", paramType = "path")
    })
    @ResponseBody
    public Response kline(@PathVariable("symbol") String symbol,
                          @PathVariable("lintType") String lintType,
                          @PathVariable("size") Integer size) {
        if (StringUtils.isEmpty(symbol) || StringUtils.isEmpty(lintType)) {
            log.warn("请求参数不能为空");
            throw new GlobalDefaultException(-2);
        }
        if (size == null) {
            size = 100;
        }
        //K线数据 调用火币API获取
        if (symbol.equalsIgnoreCase("BTCUSDT") || symbol.equalsIgnoreCase("EOSUSDT")
                || symbol.equalsIgnoreCase("ETHUSDT") || symbol.equalsIgnoreCase("XRPUSDT")
                || symbol.equalsIgnoreCase("BCHUSDT") || symbol.equalsIgnoreCase("LTCUSDT")) {
            symbol = symbol.toLowerCase();
            //缓存获取数据 不存在则调用火币API
            String redisKLineKey = "kline:" + symbol + ":" + size;
            List<Candlestick> list = (List<Candlestick>) redisTemplate.opsForValue().get(redisKLineKey);
            if (list != null && list.size() > 0) {
                return Response.ok(list);
            }
            //调用火币API获取数据
            CandlestickIntervalEnum csi = CandlestickIntervalEnum.getCsi(lintType);
            if (csi == null) {
                return Response.err(ResultCode.K_LINT_TYPE_ERROR);
            }
            MarketClient marketClient = MarketClient.create(new HuobiOptions());
            list = marketClient.getCandlestick(CandlestickRequest.builder()
                    .size(size)
                    .interval(csi)
                    .symbol(symbol)
                    .build());
            redisTemplate.opsForValue().set(redisKLineKey, list, 100L, TimeUnit.MILLISECONDS);
            return Response.ok(list);
        } else {
            String redisKey = new StringBuffer(REDIS_KEY_TRADE_KLINE).append(symbol).append(":").append(lintType).toString();
            List<Object> kline = redisTemplate.opsForList().range(redisKey, 0, 999);
            //Collections.reverse(kline);
            return Response.ok(kline);
        }
        /*if (symbol.equalsIgnoreCase("BTCUSDT") || symbol.equalsIgnoreCase("EOSUSDT")
                || symbol.equalsIgnoreCase("ETHUSDT") || symbol.equalsIgnoreCase("XRPUSDT")
                || symbol.equalsIgnoreCase("BCHUSDT") || symbol.equalsIgnoreCase("LTCUSDT")) {
            symbol = symbol.toLowerCase();
            //调用火币API获取数据
            CandlestickIntervalEnum csi = CandlestickIntervalEnum.getCsi(lintType);
            if (csi == null) {
                return Response.err(ResultCode.K_LINT_TYPE_ERROR);
            }
            String kline = symbol + ":" + size;
            MarketClient marketClient = MarketClient.create(new HuobiOptions());
            marketClient.subCandlestick(
                    SubCandlestickRequest.builder().symbol(symbol).interval(csi).build(),
                    (candlestick) -> {
                        WebSocketServer.sendToAll(JsonUtils.writeValueAsString(candlestick), kline);
                    }
            );
            return Response.ok();
        } else {
            String redisKey = new StringBuffer(REDIS_KEY_TRADE_KLINE).append(symbol).append(":").append(lintType).toString();
            List<Object> kline = redisTemplate.opsForList().range(redisKey, 0, 999);
            Collections.reverse(kline);
            return Response.ok(GsonUtil.toJson(kline));
        }*/
    }

    /**
     * 获取市场合并深度
     *
     * @param symbol    交易对标识符
     * @param mergeType 合并深度类型
     */
    @GetMapping(value = "/depth/{symbol}/{mergeType}")
    @ApiOperation(value = "币币交易市场深度", notes = "币币交易市场深度", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "symbol", value = "交易对标识符", required = true, dataType = "String", paramType = "path"),
            @ApiImplicitParam(name = "mergeType", value = "合并深度类型", required = true, dataType = "String", paramType = "path")
    })
    public Response depth(@PathVariable("symbol") String symbol,
                          @PathVariable("mergeType") String mergeType) {
        if (StringUtils.isEmpty(symbol) || StringUtils.isEmpty(mergeType)) {
            log.warn("请求参数不能为空");
            throw new GlobalDefaultException(-2);
        }
        //合并深度 调用火币API获取
        if (symbol.equalsIgnoreCase("BTCUSDT") || symbol.equalsIgnoreCase("EOSUSDT")
                || symbol.equalsIgnoreCase("ETHUSDT") || symbol.equalsIgnoreCase("XRPUSDT")
                || symbol.equalsIgnoreCase("BCHUSDT") || symbol.equalsIgnoreCase("LTCUSDT")) {
            symbol = symbol.toLowerCase();

            String redisDepthKey = "depth:" + symbol + ":" + mergeType;
            MarketDepth marketDepth = (MarketDepth) redisTemplate.opsForValue().get(redisDepthKey);
            if (marketDepth != null) {
                return Response.ok(marketDepth);
            }
            DepthStepEnum ds = DepthStepEnum.getDs(mergeType);
            if (ds == null) {
                log.warn("请求参数错误");
                throw new GlobalDefaultException(-2);
            }
            MarketClient marketClient = MarketClient.create(new HuobiOptions());
            marketDepth = marketClient.getMarketDepth(MarketDepthRequest.builder()
                    .symbol(symbol)
                    .depth(DepthSizeEnum.SIZE_20)
                    .step(ds)
                    .build());
            redisTemplate.opsForValue().set(redisDepthKey, marketDepth, 100L, TimeUnit.MILLISECONDS);
            return Response.ok(marketDepth);
        } else {
            DepthMergeType depthMergeType = DepthMergeType.getByCode(mergeType);
            if (depthMergeType == null) {
                log.warn("请求参数错误");
                throw new GlobalDefaultException(-2);
            }
            Market market = marketService.queryBySymbol(symbol);
            if (market == null) {
                log.error("请求参数错误");
                throw new GlobalDefaultException(-2);
            }
            try {
                switch (depthMergeType) {
                    case DEFAULT:
                        return Response.ok(entrustOrderService.DEPTH_CACHE_INSTANCE().get(market.getId()));
                    case LOW:
                        return Response.ok(entrustOrderService.MERGE_LOW_DEPTH_CACHE_INSTANCE().get(market.getId()));
                    case HIGH:
                        return Response.ok(entrustOrderService.MERGE_HIGH_DEPTH_CACHE_INSTANCE().get(market.getId()));
                    default:
                        return Response.ok();
                }
            } catch (ExecutionException e) {
                log.error("获取市场深度失败，symbol：{}，mergeType：{}", symbol, mergeType);
                throw new GlobalDefaultException(-1);
            }
        }
    }

    /**
     * 获取交易对行情数据
     *
     * @param symbol 交易对标识符
     * @return
     */
    @GetMapping(value = "/ticker/{symbol}")
    @ApiOperation(value = "币币交易实时行情", notes = "币币交易实时行情", httpMethod = "GET")
    @ApiImplicitParam(name = "symbol", value = "交易对标识符", required = true, dataType = "String", paramType = "path")
    public Object ticker(@PathVariable("symbol") String symbol) {
        if (StringUtils.isEmpty(symbol)) {
            log.warn("请求参数不能为空");
            throw new GlobalDefaultException(-2);
        }
        String redisKey = new StringBuffer(REDIS_KEY_TRADE_KLINE).append(symbol).append(":").append(KlineType.FIVE_SECONDS.getValue()).toString();
        Object kline = redisTemplate.opsForList().index(redisKey, 0);
        return Response.ok(GsonUtil.toJson(kline));
    }

    /**
     * 获取最新成交列表
     *
     * @param symbol 交易对标识符
     * @return
     */
    @GetMapping(value = "/trades/{symbol}/{size}")
    @ApiOperation(value = "币币交易最新成交列表", notes = "币币交易最新成交列表", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "symbol", value = "交易对标识符", required = true, dataType = "String", paramType = "path"),
            @ApiImplicitParam(name = "size", value = " 返回数据条数", required = false, dataType = "int", paramType = "path")
    })
    @ResponseBody
    public Response trades(@PathVariable("symbol") String symbol, @PathVariable("size") Integer size) {

        if (StringUtils.isEmpty(symbol)) {
            log.error("请求参数不能为空");
            throw new GlobalDefaultException(-2);
        }
        if (size == null || size < 1) {
            size = 100;
        }
        //调用火币API获取最近成交数据
        if (symbol.equalsIgnoreCase("BTCUSDT") || symbol.equalsIgnoreCase("EOSUSDT")
                || symbol.equalsIgnoreCase("ETHUSDT") || symbol.equalsIgnoreCase("XRPUSDT")
                || symbol.equalsIgnoreCase("BCHUSDT") || symbol.equalsIgnoreCase("LTCUSDT")) {
            //调用火币API获取数据
            symbol = symbol.toLowerCase();

            String redisMarketHistory = "market:history:trade:" + symbol + ":" + size;
            List<MarketTrade> list = (List<MarketTrade>) redisTemplate.opsForValue().get(redisMarketHistory);
            if (!CollectionUtils.isEmpty(list)) {
                return Response.ok(list);
            }
            MarketClient marketClient = MarketClient.create(new HuobiOptions());
            list = marketClient.getMarketHistoryTrade(
                    MarketHistoryTradeRequest.builder()
                            .symbol(symbol)
                            .size(size)
                            .build()
            );
            redisTemplate.opsForValue().set(redisMarketHistory, list, 100L, TimeUnit.MILLISECONDS);
            return Response.ok(list);
        } else {
            Market market = marketService.queryBySymbol(symbol);
            if (market == null) {
                log.error("参数错误");
                throw new GlobalDefaultException(-2);
            }
            try {
                return Response.ok(turnoverOrderService.DEAL_ORDER_CACHE_INSTANCE().get(market.getId()));
            } catch (ExecutionException e) {
                log.error("币币交易最新成交列表失败，symbol：{}", symbol);
                throw new GlobalDefaultException(-1);
            }
        }
    }

    /**
     * 最近24小时行情数据
     *
     * @param symbol 交易对标识符
     * @return
     */
    @GetMapping(value = "/latestMarket/{symbol}")
    @ApiOperation(value = "最近24小时行情数据", notes = "最近24小时行情数据", httpMethod = "GET")
    @ApiImplicitParam(name = "symbol", value = "交易对标识符", required = true, dataType = "String", paramType = "path")
    public Response latestMarket(@PathVariable("symbol") String symbol) {
        if (StringUtils.isEmpty(symbol)) {
            log.error("请求参数不能为空");
            throw new GlobalDefaultException(-2);
        }
        if (symbol.equalsIgnoreCase("BTCUSDT") || symbol.equalsIgnoreCase("EOSUSDT")
                || symbol.equalsIgnoreCase("ETHUSDT") || symbol.equalsIgnoreCase("XRPUSDT")
                || symbol.equalsIgnoreCase("BCHUSDT") || symbol.equalsIgnoreCase("LTCUSDT")) {
            symbol = symbol.toLowerCase();
            String redisLatestMarket = "latestMarket:" + symbol;
            MarketDetail marketDetail = (MarketDetail) redisTemplate.opsForValue().get(redisLatestMarket);
            if (marketDetail != null) {
                return Response.ok(marketDetail);
            }
            MarketClient marketClient = MarketClient.create(new HuobiOptions());
            marketDetail = marketClient.getMarketDetail(MarketDetailRequest.builder().symbol(symbol).build());
            redisTemplate.opsForValue().set(redisLatestMarket, marketDetail, 100L, TimeUnit.MILLISECONDS);
            return Response.ok(marketDetail);
        } else {
            return Response.ok();
        }
    }

    /**
     * 获取币种当前价格以及今日涨跌幅
     *
     * @param symbol
     * @return
     */
    @GetMapping("/currentPrice/{symbol}")
    @ApiOperation(value = "获取币种当前价格以及今日涨跌幅", notes = "获取币种当前价格以及今日涨跌幅", httpMethod = "GET")
    @ApiImplicitParam(name = "symbol", value = "交易对标识符", required = true, dataType = "String", paramType = "path")
    public Response currentPrice(@PathVariable("symbol") String symbol) {
        if (StringUtils.isEmpty(symbol)) {
            log.error("请求参数不能为空");
            throw new GlobalDefaultException(-2);
        }
        Map<String, String> result = new HashMap<>(4);
        if (symbol.equalsIgnoreCase("AQSUSDT") || symbol.equalsIgnoreCase("AQPUSDT")) {
            //TODO AQS  AQP 价格以及涨幅数据获取
            BigDecimal price;
            if (symbol.equalsIgnoreCase("AQSUSDT")) {
                String redisKeyAqsCurrentPrice = "current:price:aqs";
                price = (BigDecimal) redisTemplate.opsForValue().get(redisKeyAqsCurrentPrice);
            } else {
                String redisKeyAqpCurrentPrice = "current:price:aqp";
                price = (BigDecimal) redisTemplate.opsForValue().get(redisKeyAqpCurrentPrice);
            }
            result.put("increase", "0.00%");
            result.put("symbol", symbol);
            result.put("priceUsdt", String.valueOf(price));
        } else {
            //调用火币API获取数据
            symbol = symbol.toLowerCase();
            String redisCurrentPrice = "currentPrice:" + symbol;
            Map<String, String> data = (Map<String, String>) redisTemplate.opsForValue().get(redisCurrentPrice);
            if (data != null && !data.isEmpty()) {
                return Response.ok(data);
            }
            MarketClient marketClient = MarketClient.create(new HuobiOptions());
            List<Candlestick> list = marketClient.getCandlestick(CandlestickRequest.builder()
                    .size(1)
                    .interval(CandlestickIntervalEnum.DAY1)
                    .symbol(symbol.toLowerCase())
                    .build());
            Candlestick candlestick = list.get(0);
            //涨跌幅 正数为涨 负数为跌
            BigDecimal increase = candlestick.getClose().subtract(candlestick.getOpen()).multiply(BigDecimal.valueOf(100)).divide(candlestick.getOpen(), 2, RoundingMode.DOWN);
            result.put("increase", increase + "%");
            result.put("symbol", symbol);
            result.put("priceUsdt", candlestick.getClose().toPlainString());
            redisTemplate.opsForValue().set(redisCurrentPrice, result, 100L, TimeUnit.MILLISECONDS);
        }
        return Response.ok(result);
    }

    /****************************************** 微服务 *******************************************************/
    /**
     * 获取所有币币交易市场
     *
     * @return
     */
    @GetMapping("/all")
    @ApiOperation(value = "获取所有币币交易市场", notes = "获取所有币币交易市场", httpMethod = "GET")
    public Response tradeMarkets() {
        String redisMarketInfo = "market:info:all";
        List<MarketDTO> data = (List<MarketDTO>) redisTemplate.opsForValue().get(redisMarketInfo);
        if (data != null) {
            return Response.ok(data);
        }
        List<MarketDTO> marketDTOS = marketService.queryByType(MarketType.TRADE);
        for (MarketDTO marketDTO : marketDTOS) {
            String symbol = marketDTO.getSymbol().toLowerCase();
            if (!symbol.equalsIgnoreCase("AQPUSDT") && !symbol.equalsIgnoreCase("AQSUSDT")) {
                //调用火币API获取数据
                Candlestick candlestick;
                try {
                    MarketClient marketClient = MarketClient.create(new HuobiOptions());
                    List<Candlestick> list = marketClient.getCandlestick(CandlestickRequest.builder()
                            .size(1)
                            .interval(CandlestickIntervalEnum.DAY1)
                            .symbol(symbol)
                            .build());
                    candlestick = list.get(0);
                    //涨跌幅 正数为涨 负数为跌
                    BigDecimal increase = candlestick.getClose().subtract(candlestick.getOpen()).multiply(BigDecimal.valueOf(100)).divide(candlestick.getOpen(), 2, RoundingMode.DOWN);
                    marketDTO.setIncrease(increase + "%");
                    marketDTO.setPriceUsdt(candlestick.getClose().toPlainString());
                    marketDTO.setOpenPrice(candlestick.getOpen());
                } catch (Exception e) {
                    log.warn("调用火币API获取数据异常 symbol={} e={}", symbol, e.getMessage());
                }
            }
        }
        redisTemplate.opsForValue().set(redisMarketInfo, marketDTOS, 100L, TimeUnit.MILLISECONDS);
        System.out.println("调用SUCCESS222 -- " + marketDTOS.size());
        return Response.ok(marketDTOS);
    }

    @GetMapping("/all2")
    public List<MarketDTO> tradeMarkets2() {
        String redisMarketInfo = "market:info:all";
        List<MarketDTO> data = (List<MarketDTO>) redisTemplate.opsForValue().get(redisMarketInfo);
        if (data != null) {
            return data;
        }
        List<MarketDTO> marketDTOS = marketService.queryByType(MarketType.TRADE);
        for (MarketDTO marketDTO : marketDTOS) {
            String symbol = marketDTO.getSymbol().toLowerCase();
            if (!symbol.equalsIgnoreCase("AQPUSDT") && !symbol.equalsIgnoreCase("AQSUSDT")) {
                //调用火币API获取数据
                Candlestick candlestick;
                try {
                    MarketClient marketClient = MarketClient.create(new HuobiOptions());
                    List<Candlestick> list = marketClient.getCandlestick(CandlestickRequest.builder()
                            .size(1)
                            .interval(CandlestickIntervalEnum.DAY1)
                            .symbol(symbol)
                            .build());
                    candlestick = list.get(0);
                    //涨跌幅 正数为涨 负数为跌
                    BigDecimal increase = candlestick.getClose().subtract(candlestick.getOpen()).multiply(BigDecimal.valueOf(100)).divide(candlestick.getOpen(), 2, RoundingMode.DOWN);
                    marketDTO.setIncrease(increase + "%");
                    marketDTO.setPriceUsdt(candlestick.getClose().toPlainString());
                    marketDTO.setOpenPrice(candlestick.getOpen());
                } catch (Exception e) {
                    log.warn("调用火币API获取数据异常 symbol={} e={}", symbol, e.getMessage());
                }
            } else {
                BigDecimal priceUsdt;
                if (symbol.equalsIgnoreCase("AQPUSDT")) {
                    priceUsdt = (BigDecimal) redisTemplate.opsForValue().get("current:price:aqp");
                } else {
                    priceUsdt = (BigDecimal) redisTemplate.opsForValue().get("current:price:aqs");
                }
                //TODO AQS AQP信息获取
                marketDTO.setIncrease("0%");
                marketDTO.setPriceUsdt(priceUsdt.setScale(8, RoundingMode.DOWN).toPlainString());
                marketDTO.setOpenPrice(BigDecimal.ONE);
            }
        }
        redisTemplate.opsForValue().set(redisMarketInfo, marketDTOS, 100L, TimeUnit.MILLISECONDS);
        return marketDTOS;
    }

    /**
     * 根据marketIds获取币币交易市场
     *
     * @return
     */
    @ApiIgnore
    @PostMapping("/queryTradeMarkets")
    public List<TradeMarketDTO> queryTradeMarkets() {
        Collection<TradeMarketDTO> data = marketService.TRADE_MARKET_CACHE_INSTANCE().asMap().values();
        List<TradeMarketDTO> tradeMarkets = new ArrayList<>(data);
        Collections.sort(tradeMarkets);
        return tradeMarkets;
    }

    /**
     * 根据marketIds获取币币交易市场
     *
     * @return
     */
    @ApiOperation(value = "根据marketIds获取币币交易市场", notes = "根据marketIds获取币币交易市场", httpMethod = "POST")
    @ApiImplicitParam(name = "marketIds", value = "marketIds,多个则英文逗号分隔开", required = true, dataType = "String", paramType = "path")
    @PostMapping("/queryTradeMarketsByIds")
    public List<TradeMarketDTO> queryTradeMarketsByIds(String marketIds) {
        ImmutableList<TradeMarketDTO> data = marketService.queryByType(MarketType.TRADE, marketIds);
        List<TradeMarketDTO> tradeMarkets = new ArrayList<>(data);
        Collections.sort(tradeMarkets);
        return tradeMarkets;
    }

    /**
     * 刷新币币交易市场
     *
     * @param marketId 交易对ID
     * @return
     */
    @GetMapping("/refresh/{marketId}")
    public boolean refreshMarket(@PathVariable("marketId") Long marketId) {
        marketService.TRADE_MARKET_CACHE_INSTANCE().refresh(marketId);
        return true;
    }

    /**
     * 根据Symbol 获取 marketId
     */
    @GetMapping("/getBySymbol/{symbol}")
    public Object getBySymbol(@PathVariable("symbol") String symbol) {
        EntityWrapper<Market> e = new EntityWrapper<>();
        e.eq("symbol", symbol);
        Market market = marketService.selectOne(e);
        if (Optional.ofNullable(market).isPresent()) {
            return market.getId();
        }
        return 0L;
    }

}
